package com.stars.easyms.rest.filter;

import com.stars.easyms.rest.bean.EasyMsRestContext;
import com.stars.easyms.rest.handler.EasyMsRequestHandler;
import com.stars.easyms.rest.handler.EasyMsResponseHandler;
import com.stars.easyms.rest.handler.EasyMsRestRequestHandler;
import com.stars.easyms.rest.properties.EasyMsRestProperties;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>className: EasyMsRestFilter</p>
 * <p>description: rest过滤器</p>
 *
 * @author guoguifang
 * @version 1.2.2
 * @date 2019/7/19 16:05
 */
public final class EasyMsRestFilter implements Filter {

    private final EasyMsRestRequestHandler easyMsRestRequestHandler;

    private final EasyMsRequestHandler easyMsRequestHandler;

    private final EasyMsResponseHandler easyMsResponseHandler;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        // 生成本地rest的上下文，并将request和response放入上下文中
        EasyMsRestContext easyMsRestContext = new EasyMsRestContext();
        easyMsRestContext.setHttpServlet(httpServletRequest, httpServletResponse);
        try {

            // 如果EasyMsRestRequestEntity或者RequestMappingPathForRestInfo为空则直接跳过
            easyMsRequestHandler.resolveRequest(easyMsRestContext);
            if (easyMsRestContext.getEasyMsRequestEntity() == null || !easyMsRestContext.isEasyMsRest()) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }

            // 到达这里的只有EasyMs相关的接口，执行easy-ms的rest请求
            easyMsRestRequestHandler.execute(easyMsRestContext);

        } catch (Throwable t) {

            // 如果有异常信息则将异常信息放入rest上下文中
            easyMsRestContext.setThrowable(t);
            easyMsRestContext.setReturnResponseBody(true);

        } finally {

            // 处理响应结果
            if (easyMsRestContext.getEasyMsRequestEntity() != null) {
                easyMsResponseHandler.handleResponse(easyMsRestContext);
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
        // Intentionally blank
    }

    @Override
    public void destroy() {
        // Intentionally blank
    }

    public EasyMsRestFilter(EasyMsRestProperties easyMsRestProperties) {
        this.easyMsRestRequestHandler = new EasyMsRestRequestHandler(easyMsRestProperties);
        this.easyMsRequestHandler = new EasyMsRequestHandler(easyMsRestProperties);
        this.easyMsResponseHandler = new EasyMsResponseHandler(easyMsRestProperties);
    }
}